<template>
    <Form ref="Form" :model="fields" :rules="rules">
        <Row :gutter="16">
            <Col span="24">
                <FormItem label="上级分类" prop="parent_id">
                    <Cascader :data="categories" trigger="hover" change-on-select v-model="fields.parent_id"></Cascader>
                </FormItem>
            </Col>
        </Row>
        <Row :gutter="16">
            <Col span="12">
                <FormItem label="分类名称" prop="name">
                    <Input v-model="fields.name" placeholder="请输入分类名称" @on-blur="formatCode"></Input>
                </FormItem>
            </Col>
            <Col span="8">
                <FormItem label="分类标识" prop="code">
                    <Input v-model="fields.code" placeholder="自动生成"></Input>
                </FormItem>
            </Col>
            <Col span="4">
                <FormItem label="排序" prop="sort">
                    <Input v-model="fields.sort" number placeholder="排序，数字大的靠前"></Input>
                </FormItem>
            </Col>
        </Row>
        <Row>
            <Col>
                <FormItem>
                    <Button type="primary" @click="handleSubmit">提交</Button>
                    <Button type="ghost" style="margin-left: 10px" @click="handleCancel">取消</Button>
                </FormItem>
            </Col>
        </Row>
    </Form>
</template>

<script>
    import util from '@/libs/util';
    export default {
        data () {
            const valideParentId = (rule, value, callback) => {
                if (!(value instanceof Array) || value.length <= 0) {
                    callback(new Error('请选择父级分类'));
                } else {
                    callback();
                }
            };

            return {
                fields: {
                    parent_id: [],
                    code: '',
                    name: '',
                    sort: 0
                },

                rules: {
                    parent_id: [
                        { validator: valideParentId },
                    ],
                    code: [
                        { required: true, message: '请输入分类标识', trigger: 'blur'},
                    ],
                    name: [
                        { required: true, message: '请输入分类名称', trigger: 'blur'},
                        { type: 'string', min: 2, max: 20, message: '名称格式必须是2~20个字符' }
                    ],
                    sort: [
                        { type: 'number', message: '请输入数字. 最小值0,最大值999' }
                    ]
                },

                categories: []
            }
        },

        props: {
            rootNode: Object
        },

        created () {
            this.initCategories(0, (tree, selected) => {
                this.categories = tree;
            });
        },

        methods: {
            initCategories (id, callback) {
                util.api().get(`/admin/api/categories/0/selected/parents`).then((resp) => {
                    const formatTree = (arr) => {
                        let categories = [];
                        for (let i in arr) {
                            let node = {};
                            node.value = arr[i].id;
                            node.label = arr[i].name;
                            node.disabled = arr[i].disabled;
                            if (arr[i].hasOwnProperty('children')) {
                                node.children = formatTree(arr[i].children);
                            }
                            if (id == node.value) {
                                node.disabled = true;
                            }
                            categories.push(node);
                        }
                        return categories;
                    };

                    const tree = formatTree(resp.data.data.tree);
                    tree.unshift({
                        value: 0,
                        label: '顶级分类'
                    });
                    callback(tree, []);
                }).catch((e) => {
                    if (e.response) {
                        this.$Notice.error({ title: '获取分类失败', desc: e.response.data.message});
                    } else {
                        this.$Message.error('获取分类失败');
                    }
                    callback([], []);
                });
            },

            handleSubmit () {
                this.$refs.Form.validate((valid) => {
                    if (valid) {
                        this.add(this.fields);
                    } else {
                        this.$Message.error('验证失败');
                    }
                });
            },

            handleCancel () {
                this.rootNode.addModel = false;
            },

            formatCode () {
                if (this.fields.name.length > 0) {
                    util.api().get(`/admin/api/categories/format/code/${this.fields.name}`).then((resp) => {
                        this.fields.code = resp.data.data;
                    }).catch((e) => {
                        util.handleApiException(e, this, '生成分类标识失败');
                    })
                }
            },

            add (data) {
                data.parent_id = data.parent_id.pop();
                util.api().post(`/admin/api/categories`, data).then((resp) => {
                    if (resp.data.status == true) {
                        this.$Message.success(resp.data.message);
                        this.rootNode.addModel = false;
                        this.$emit('on-change', resp.data.data);
                        this.initCategories(0, (tree, selected) => {
                            this.categories = tree;
                        });
                    } else {
                        this.$Message.error(resp.data.message);
                    }
                }).catch((e) => {
                    if (e.response) {
                        if (e.response.status == 422) {
                            if (e.response.data.hasOwnProperty('errors')) {
                                for (let i in e.response.data.errors) {
                                    this.$Notice.error({ title: '表单数据验证失败', desc: e.response.data.errors[i][0] });
                                }
                            }
                        } else {
                            this.$Message.error(e.response.data.message);
                        }
                    }  else {
                        this.$Message.error('网络请求异常');
                    }
                })
            }
        }
    }
</script>